<?php

class AjaxController extends CController {
    
    public function filters() {
        return array( 'ajaxOnly' );
    }
    
    public function actionGetUsernames($login) {
        $data = Yii::app()->db->createCommand()->select('displayName')->from('users')->where("displayName like \"%$login%\"")->limit(5)->queryAll();
        echo $this->renderPartial('userListAutoComplete', array('data'=>$data), true);
    }
    
    public function actionCheckUserName($login) {
        $user = Yii::app()->db->createCommand()->select('userid')->from('users')->where('displayName="'.$login.'"')->query()->read();
        if(!empty($user)) echo $user['userid'];
    }
    
    public function actionGetSubCats($catid) {
        $cats = Yii::app()->db->createCommand()->select('name, catId')->from('partners_cat')->where("parentId=$catid")->queryAll();
        echo $this->renderPartial('getSubCats', array('cats'=>$cats), true);
    }
    
    public function actionGetSort($catid, $partner_id) {
        $dataSort1 = new CActiveDataProvider('PartnerCatRaiting', array('criteria'=>array('condition'=>"type=1 AND catId=$catid", 'order'=>'catRatingId ASC')));
        $dataSort2 = new CActiveDataProvider('PartnerCatRaiting', array('criteria'=>array('condition'=>"type=2 AND catId=$catid", 'order'=>'catRatingId ASC')));
        $sort1=$sort2=array();
        if($partner_id){
            $sort1 = PartnerRaiting::model()->findAllByAttributes(array('partnerid'=>$partner_id, 'type'=>'1'),  array('order' => 'catRatingId ASC'));
            $sort2 = PartnerRaiting::model()->findAllByAttributes(array('partnerid'=>$partner_id, 'type'=>'2'), array('order' => 'catRatingId ASC'));
        }
        echo $this->renderPartial('getSort', array('dataSort1'=>$dataSort1, 'dataSort2'=>$dataSort2, 'sort1' => $sort1, 'sort2' => $sort2), true);
    }
    
    public function actionGetSubCatsSort($catsid, $partner_id) {
        $cats = Yii::app()->db->createCommand()->select('catId, name')->from('partners_cat')->where('catId in('.$catsid.')')->queryAll();
        if(!empty($cats)) {
            $idArr = array();
            for($i=0; $i<count($cats); $i++) $idArr[] = $cats[$i]['catId'];
            $sortParams = Yii::app()->db->createCommand()->select('*')->from('partners_catraitings')->where(array('in', 'catId', $idArr))->queryAll();
            if(!empty($sortParams)) {
                for($i=0; $i<count($cats); $i++) {
                    for($j=0; $j<count($sortParams); $j++) {
                        if($sortParams[$j]['catId'] == $cats[$i]['catId']) {
                            if($sortParams[$j]['type'] == 1) {
                                $cats[$i]['sort1'][] = $sortParams[$j];
                            } else $cats[$i]['sort2'][] = $sortParams[$j];
                        }
                    }
                }
            }
            echo $this->renderPartial('getSubCatsSort', array('cats'=>$cats), true);
        }
    }
    
    public function actionGetPartnersList() {
        if(!isset($_POST['catsid'])) die;
        $modelName = isset($_POST['modelName']) ? $_POST['modelName'] : 'News' ;
        $title = isset($_POST['title']) ? $_POST['title'] : 'Список партнерок:';
        $res = Yii::app()->db->createCommand()->select('c.catId, c.name as catName, p.name, p.partnerid')->from('partners p')->join('partners_cat c', 'c.catId=p.catId')->where("p.catId in(".substr($_POST['catsid'], 0, -1).")")->queryAll();
        echo !empty($res) ? $this->renderPartial('partnerCheckBoxList', array('res'=>$res, 'modelName'=>$modelName, 'title'=>$title), true) : '';
    }
    
    public function actionGetForumList() {
        if(!isset($_POST['catsid'])) die;
        $modelName = isset($_POST['modelName']) ? $_POST['modelName'] : 'User' ;
        $data = Yii::app()->db->createCommand()->select('p.name, p.partnerid, p.catId, c.name as catName')->from('partners p')->join('partners_cat c', 'c.catId=p.catId')->where('p.catId in('.substr($_POST['catsid'], 0, -1).')')->queryAll();
        if(!empty($data)) echo $this->renderPartial('forumCheckBoxList', array('data'=>$data, 'modelName'=>$modelName), true);
    }
    
    public function actionSubscribe($type, $email, $typeId=0) {
        $data = Yii::app()->db->createCommand(array('select' => 'id','from' => 'subscribers','where' => "email=:email and type=:type and typeId=:typeId",'params' => array(':email'=>$email, ':type'=>$type, ':typeId'=>$typeId)))->queryRow();
        if(empty($data)) {
            Yii::app()->db->createCommand()->insert('subscribers', array('type'=>$type, 'typeId'=>$typeId, 'email'=>Yii::app()->user->isGuest ? $email : Yii::app()->user->getState('email'), 'unsId'=>md5($email.time()), 'userId'=>Yii::app()->user->isGuest ? 0 : Yii::app()->user->getId(), 'date'=>time()));
            echo '1';
        } else echo '';
    }
    
    public function actionGetIsUserGuest() {
        echo Yii::app()->user->isGuest ? '1' : '' ;
    }
    
    public function actionUnsubscribeUser($userId, $type, $typeId=0) {
        if(!Yii::app()->user->isGuest && Yii::app()->user->getId() == $userId) {
            Yii::app()->db->createCommand()->delete('subscribers', "type=\"$type\" and userId=\"$userId\" and typeId=\"$typeId\"");
            echo '1';
        }
    }
    
    public function actionUnSubscribe($type, $typeId, $email) {
        Yii::app()->db->createCommand()->delete('subscribers', 'type=:type, typeId=:id, email=:email', array(':id'=>$typeId, ':email'=>$email, ':type'=>$type));
    }
    
    public function actionClickInv() {
        if(empty($_POST['id']) || empty($_POST['partnerid'])) die;
        $id = $_POST['id'];
        $partnerid = $_POST['partnerid'];
        $isUserGetInvite = Yii::app()->db->createCommand()->select('MAX(notWorkDate) as maxDate')->from('partners_invite')->where('ip="'.CHttpRequest::getUserHostAddress().'" and partnerid='.$partnerid.' and notWork=1')->queryRow();
        if(!empty($isUserGetInvite)) {
            if($isUserGetInvite['maxDate'] + 3600 > time()) {
                echo $isUserGetInvite['maxDate']; die;
            }
        }
        Yii::app()->db->createCommand()->update('partners_invite', array('notWork'=>1, 'ip'=>CHttpRequest::getUserHostAddress(), 'notWorkUser'=>Yii::app()->user->isGuest ? 0 : Yii::app()->user->getId(), 'notWorkDate'=>time()), 'id=:id', array('id'=>$id));
        $user = Yii::app()->user->isGuest ? 'Аноним' : Yii::app()->user->getState('login');
        echo "Взял $user ". Yii::app()->dateFormatter->format("dd MMMM yyyy года в HH:mm", time());
        
        #Если остался 1 инвайт - отправляем редакторам месагу.
        $countInv = Yii::app()->db->createCommand()->select('count(*) as num')->from('partners_invite')->where('notWork=0')->queryRow();
        if($countInv['num'] == 1) {
            $partner = Yii::app()->db->createCommand()->select('p.name, p.url, c.catId, c.parentId')->from('partners_invite i')->join('partners p', 'p.partnerid=i.partnerid')->join('partners_cat c', 'c.catId=p.catId')->where('i.id='.$id)->queryRow();
            $redactors = Yii::app()->db->createCommand()->select('userid, login')->from('users')->where('role="redactor"')->queryAll();
            $userIdArr = array();
            for($i=0; $i<count($redactors); $i++) $userIdArr[] = $redactors[$i]['userid'];
            $dialogs = Yii::app()->db->createCommand()->select('d.*')->from('messages_dialogs d')->where('(d.user1Id IN('.implode(',', $userIdArr).') AND d.user2Id=0) OR (d.user2Id IN('.implode(',', $userIdArr).') and d.user1Id=0)')->queryAll();
            for($i=0; $i<count($redactors); $i++) {
                $dialog = false;
                if(!empty($dialogs)) {
                    for($l=0; $l<count($dialogs); $l++) {
                        if($dialogs[$l]['user1Id'] == $redactors[$i]['userid'] || $dialogs[$l]['user2Id'] == $redactors[$i]['userid']) {
                            $dialog = $dialogs[$l]; break;
                        }
                    }
                }    
                if($dialog) {
                    $targetField = $dialog['user1Id'] == 0 ? 'user2New' : 'user1New';
                    $target = $dialog['user1Id'] == 0 ? $dialog['user2Id'] : $dialog['user1Id'];
                    $newMessTarget = $dialog['user1Id'] == 0 ? 'user2Del' : 'user1Del';;
                    Yii::app()->db->createCommand()->insert('messages', array('dialogId'=>$dialog['dialogId'], 'toId'=>$target, 'fromId'=>'0', 'sendDate'=>time(), 'message'=>$this->renderPartial('//messages/toFewInvites', array('user'=>$redactors[$i], 'partner'=>$partner), true)));
                    Yii::app()->db->createCommand()->update('messages_dialogs', array($targetField=>$target, 'lastMessId'=>Yii::app()->db->lastInsertID, $newMessTarget=>'0'), '`dialogId`='.$dialog['dialogId']);
                } else {
                    Yii::app()->db->createCommand()->insert('messages_dialogs', array('user1Id'=>$redactors[$i]['userid'], 'user2Id'=>'0', 'user1New'=>$redactors[$i]['userid'] ));
                    $dialogId = Yii::app()->db->lastInsertID;
                    Yii::app()->db->createCommand()->insert('messages', array('dialogId'=>Yii::app()->db->lastInsertID, 'toId'=>$redactors[$i]['userid'], 'fromId'=>'0', 'sendDate'=>time(), 'message'=>$this->renderPartial('//messages/toFewInvites', array('user'=>$redactors[$i], 'partner'=>$partner), true)));
                    Yii::app()->db->createCommand()->update('messages_dialogs', array('lastMessId'=>Yii::app()->db->lastInsertID), '`dialogId`='.$dialogId);
                }
            }
        }
    }
    
    public function actionWorkPartner($id) {
        if(Yii::app()->user->isGuest) die;
        $res = Yii::app()->db->createCommand()->select('id')->from('partners_users')->where('userId='.Yii::app()->user->getId().' and partnerId='.$id)->queryRow();
        if(empty($res)) {
            $count = Yii::app()->db->createCommand()->select('count(*)')->from('partners_users')->where('userId='.Yii::app()->user->getId())->queryRow();
            if($count['count(*)'] + 1 < 11) {
                Yii::app()->db->createCommand()->insert('partners_users', array('userId'=>Yii::app()->user->getId(), 'partnerId'=>$id));
            } else echo 'max';
        } else Yii::app()->db->createCommand()->delete('partners_users', 'userId='.Yii::app()->user->getId().' and partnerId='.$id);  
    }
    
    public function actionGetPartners($name) {
        $partner = Yii::app()->db->createCommand()->select('name, partnerid')->from('partners')->where('name LIKE "%'.$name.'%"')->limit(5)->queryAll();
        echo $this->renderPartial('partnersAuto', array('partner'=>$partner), true);
    }
    
    public function actionDelFofumCom($id) {
        $com = Yii::app()->db->createCommand()->select('t.themeId, t.partnerId')->from('forum_comments c')->join('forum_theme t', 't.themeId=c.themeId')->where('`comId`='.$id)->queryRow();
        if(!empty($com)) {
            if(Yii::app()->user->checkAccess('moder') || Yii::app()->user->checkAccess('admin')) {
                $images = Yii::app()->db->createCommand()->select('bigImg, smallImg')->from('forum_images')->where('`comId`='.$id)->queryAll();
                Yii::app()->db->createCommand()->delete('forum_images', '`comId`='.$id);
                Yii::app()->db->createCommand()->delete('forum_comments', '`comId`='.$id);
                for($i=0; $i<count($images); $i++) {
                    if(file_exists(Yii::getPathOfAlias('webroot').'/images/uploads/comments/'.$images[$i]['bigImg'])) 
                        unlink(Yii::getPathOfAlias('webroot').'/images/uploads/comments/'.$images[$i]['bigImg']);
                    if(file_exists(Yii::getPathOfAlias('webroot').'/images/uploads/comments/'.$images[$i]['smallImg'])) 
                        unlink(Yii::getPathOfAlias('webroot').'/images/uploads/comments/'.$images[$i]['smallImg']);
                }
                Yii::app()->db->createCommand('UPDATE `partners` SET `countComments`=countComments - 1 WHERE `partnerid`='.$com['partnerId'])->query();
                Yii::app()->db->createCommand('UPDATE `forum_theme` SET `countComments`=countComments - 1 WHERE `themeId`='.$com['themeId'])->query();
            }
        }
    }
    
    public function actionDelFofumTh($id) {
        $forumTh = Yii::app()->db->createCommand('SELECT `partnerId` FROM `forum_theme` WHERE `themeId`='.$id)->query()->read();
        if(!empty($forumTh)) {
            if(Yii::app()->user->checkAccess('moder') || Yii::app()->user->checkAccess('admin')) {
                $com = Yii::app()->db->createCommand()->select('comId')->from('forum_comments')->where('`themeId`='.$id)->queryAll();
                $comId = array();
                foreach($com as $c) $comId[] = $c['comId'];
                $images = Yii::app()->db->createCommand()->select('bigImg, smallImg')->from('forum_images')->where(array('in', 'comId', $comId))->queryAll();
                for($i=0; $i<count($images); $i++) {
                    if(file_exists(Yii::getPathOfAlias('webroot').'/images/uploads/comments/'.$images[$i]['bigImg'])) 
                        unlink(Yii::getPathOfAlias('webroot').'/images/uploads/comments/'.$images[$i]['bigImg']);
                    if(file_exists(Yii::getPathOfAlias('webroot').'/images/uploads/comments/'.$images[$i]['smallImg'])) 
                        unlink(Yii::getPathOfAlias('webroot').'/images/uploads/comments/'.$images[$i]['smallImg']);
                }
                Yii::app()->db->createCommand()->delete('forum_images', '`comId` in('.implode(',',$comId).') ');
                Yii::app()->db->createCommand()->delete('forum_theme', '`themeId`='.$id);
                Yii::app()->db->createCommand()->delete('forum_comments', '`themeId`='.$id);
                Yii::app()->db->createCommand()->delete('user_visits', '`type`="forum" and `typeId`='.$id);
                Yii::app()->db->createCommand('UPDATE `partners` SET `countComments`=countComments - '.count($com).' WHERE `partnerid`="'.$forumTh['partnerId'].'"')->query();
            }
        }     
    }
    
    public function actionBanIp($ip, $days) {
        if(Yii::app()->user->checkAccess('moder') || Yii::app()->user->checkAccess('admin')) {
            $res = Yii::app()->db->createCommand()->select('id')->from('banned_ip')->where('ip="'.$ip.'"')->queryRow();
            if($days == 0) {
                if(empty($res)) Yii::app()->db->createCommand('INSERT IGNORE INTO banned_ip (ip, userId, isForever) VALUES ("'.$ip.'", '.Yii::app()->user->getId().', 1)')->query();   
                else Yii::app()->db->createCommand()->update('banned_ip', array('isForever'=>1, 'unbanTime'=>0), 'id='.$res['id']);
            } else {
                $time = time() + $days * 86400;
                if(!empty($res)) Yii::app()->db->createCommand()->update('banned_ip', array('unbanTime'=>$time, 'isForever'=>0), 'id='.$res['id']);
                else Yii::app()->db->createCommand('INSERT IGNORE INTO banned_ip (ip, userId, unbanTime, isForever) VALUES ("'.$ip.'", '.Yii::app()->user->getId().', '.$time.', 0)')->query();    
            }
        }
    }
    
    public function actionBanUser($id, $days) {
        if(Yii::app()->user->checkAccess('moder') || Yii::app()->user->checkAccess('admin')) {
            $target = Yii::app()->db->createCommand()->select('role')->from('users')->where('`userid`='.$id)->queryRow();
            if($target['role'] == 'user') {
                if($days == 0) Yii::app()->db->createCommand()->update('users', array('isBanned'=>1, 'unblockDate'=>0), '`userid`='.$id);
                else {
                    $time = time() + $days * 86400;
                    Yii::app()->db->createCommand()->update('users', array('unblockDate'=>$time, 'isBanned'=>0), '`userid`='.$id);
                }
            } else echo 'role conflict';
        }
    }
    
    public function actionGetBrendingList() {
        if(empty($_POST['type'])) die;
        if($_POST['type'] == 'partner')
            $data = Yii::app()->db->createCommand()->select('partnerid as id, name')->from('partners')->queryAll();
        else $data = Yii::app()->db->createCommand()->select('catId as id, name')->from('partners_cat')->queryAll();
        echo CHtml::dropDownList('Brending[typeId]', 0, CHtml::listData($data, 'id', 'name'));
    }
    
    public function actionGetForumMesagePage($themeId, $need) {
        $comData = Yii::app()->db->createCommand()->select('comId')->from('forum_comments')->where("themeId=$themeId and isFirst=0")->order('comId asc')->queryAll();
        for($i=0; $i<count($comData); $i++) {
            if($need == $comData[$i]) break;
        }
        echo ceil($i/10);
    }
}